﻿using Coravel;
using Coravel.Invocable;

namespace Sample;

public static class AppWeb
{
    public static void AddApplication(this WebApplicationBuilder builder)
    {
        Config.IsDevelopment = builder.Configuration.GetSection("IsDevelopment").Get<bool>();
#if DEBUG
        Config.IsDebug = true;
#endif
        //Stopwatcher.Enabled = true;
        builder.Services.AddSample();
        builder.Services.AddKnownAdminCore(option =>
        {
            option.AddModules(ModuleHelper.AddAppModules);
        });
        builder.Services.AddKnownCells();
        builder.Services.AddKnownWeb(option =>
        {
            // 设置登录认证方式，默认Session
            //option.AuthMode = AuthMode.Cookie;
            //option.ProductId = "Test";
            //option.CheckSystem = info => Result.Error("无效密钥，请重新授权！");
            option.AddAssembly(typeof(AppWeb).Assembly);
            option.App.WebRoot = builder.Environment.WebRootPath;
            option.App.ContentRoot = builder.Environment.ContentRootPath;
            option.Database = db =>
            {
                var connString = builder.Configuration.GetSection("ConnString").Get<string>();
                //db.AddAccess<System.Data.OleDb.OleDbFactory>(connString);
                db.AddSQLite<Microsoft.Data.Sqlite.SqliteFactory>(connString);
                //db.AddSqlServer<Microsoft.Data.SqlClient.SqlClientFactory>(connString);
                //db.AddMySql<MySqlConnector.MySqlConnectorFactory>(connString);
                //db.AddPgSql<Npgsql.NpgsqlFactory>(connString);
                //db.AddDM<Dm.DmClientFactory>(connString);
                //db.SqlMonitor = c => Console.WriteLine($"{DateTime.Now:HH:mm:ss} {c}");
            };
        });

        // 注入服务
        builder.Services.AddScoped<IHomeService, HomeService>();
        builder.Services.AddScoped<IApplyService, ApplyService>();

        builder.Services.AddScheduler();
        builder.Services.AddTransient<ImportTaskJob>();
    }

    public static void UseApplication(this WebApplication app)
    {
        //使用Known框架
        app.UseKnown();
        //配置定时任务
        app.Services.UseScheduler(scheduler =>
        {
            //每5秒执行一次异步导入
            scheduler.Schedule<ImportTaskJob>().EveryFiveSeconds();
        });
    }
}

class ImportTaskJob : IInvocable
{
    public Task Invoke() => ImportHelper.ExecuteAsync();
}